package com.wpre.luckymagicautotest.common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2025-02-23
 * Time: 15:55
 */
public class Utils {
    public static WebDriver driver;

    //创建驱动对象
    public static WebDriver createDriver() {
        if (driver == null) {
            WebDriverManager.chromedriver();
            ChromeOptions options = new ChromeOptions();
            //允许访问所有的链接
            options.addArguments("--remote-allow-origins=*");
            driver = new ChromeDriver(options);
        }
        return driver;
    }

    //屏幕截图
    public void getScreenShot(String str) throws IOException {
        File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        //文件保存格式
        //                  ./src/test/image
        //                                 /2025-02-22
        //                                            /test01-1114.png
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");//文件夹,年月日格式
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");//文件名称,日期时间格式,时间精确到毫秒

        String dirTime = sim1.format(System.currentTimeMillis());//文件夹名称
        String fileTime = sim2.format(System.currentTimeMillis());//文件名称

        String fileName = "./src/test/image/" + dirTime + "/" + str + "-" + fileTime + ".png";

        FileUtils.copyFile(src, new File(fileName));

    }

    public Utils(String url) {

        //调用driver对象
        driver = createDriver();
        //访问url
        driver.get(url);
        //隐式等待
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));

    }
}
